package com.shenzhen.horselive.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.citywheel.CustomConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AddressBean;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.databinding.ActivityAddAddrBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;

public class AddAddrActivity extends AppBarActivity {

    private final    int TYPE_ADD = 0;
    private  final   int TYPE_EDITE = 1;
    private  int  type;

    ActivityAddAddrBinding  binding;
    CityPickerView mPicker=new CityPickerView();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPicker.init(this);
        binding=ActivityAddAddrBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initViews();
        setStyleDark();



    }

    AddressBean  bean;
    private   String  city;
    private  String  provice;
    private  String  connty;
    private void initViews() {
        type = getIntent().getIntExtra("type",TYPE_ADD);
        if (type==TYPE_ADD)
        {
            //增加地址
            setTitle("新增收货地址");
        }
        else
        {
            //修改地址
            setTitle("编辑收货地址");
            setMenuText("删除");
            //初始化

             bean  = (AddressBean) getIntent().getSerializableExtra("data");
            if ("1".equals(bean.getDef()))
            {
                binding.swithCheck.setChecked(true);
            }
            else
            {
                binding.swithCheck.setChecked(false);
            }
             provice = bean.getProvince();
             city =bean.getCity();
             connty = bean.getCounty();
            binding.etName.setText(bean.getContactsName());
            binding.etPhone.setText(bean.getContactsPhone());
            binding.tvAddr.setText(bean.getProvince()+bean.getCity()+bean.getCounty());
            binding.etAddrDetails.setText(bean.getAddress());
        }


        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type==TYPE_ADD)
                {
                    add();
                }
                else
                {
                    update();
                }

            }
        });


        binding.tvAddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             hideSoftKeyboard();
             openCityPick();
            }
        });



    }

    private void update() {
        //更新
        String  name =  binding.etName.getText().toString();
        if (TextUtils.isEmpty(name))
        {
            showToast("请输入收货人姓名");

            return;
        }
        String  phone =  binding.etPhone.getText().toString();
        if (TextUtils.isEmpty(phone))
        {
            showToast("请填写电话");

            return;
        }
        String  tvaddr =  binding.tvAddr.getText().toString();
        if (TextUtils.isEmpty(tvaddr))
        {
            showToast("请填写地址");

            return;
        }

        String  addr_details =  binding.etAddrDetails.getText().toString();
        if (TextUtils.isEmpty(addr_details))
        {
            showToast("请填写详细地址");
            return;
        }

        ApiFactory.getApiService().updateAddr(User.get().getMyInfo().getToken(),bean.getId()+""
                ,name,phone,provice,city,connty,addr_details,binding.swithCheck.isChecked()?"1":"0"
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("修改成功");
                            Intent  intent  =new Intent();
                            setResult(1001,intent);
                            finish();
                        }else
                        {
                            showToast(commResponseBean.getErrMessage());

                        }
                    }
                });

    }

    //打开城市选择器
    private void openCityPick() {
//        AreaPicker areaPicker = new AreaPicker();
//        areaPicker.setListener(new AreaPicker.AreaPickerListener() {
//            @Override
//            public void onPicked(String province, String city) {
//                binding.tvChooseCity.setText(province+""+city);
//            }
//        });
//        areaPicker.show(getSupportFragmentManager());

        //监听选择点击事件及返回结果
//添加默认的配置，不需要自己定义，当然也可以自定义相关熟悉，详细属性请看demo
        CityConfig cityConfig = new CityConfig.Builder().build();
        mPicker.setConfig(cityConfig);
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                //省份province
                //城市city
                //地区district
                provice = province.getName();
                AddAddrActivity.this.city = city.getName();
                AddAddrActivity.this.connty = district.getName();
                binding.tvAddr.setText(provice+city.getName()+district.getName());

            }

            @Override
            public void onCancel() {

            }
        });

        //显示
        mPicker.showCityPicker( );
    }


    private void add() {
        String  name =  binding.etName.getText().toString();
        if (TextUtils.isEmpty(name))
        {
            showToast("请输入收货人姓名");

            return;
        }
        String  phone =  binding.etPhone.getText().toString();
        if (TextUtils.isEmpty(phone))
        {
            showToast("请填写电话");

            return;
        }

       if (city==null)
       {
           showToast("请选择省市区地址");

        return;

       }
       if (provice==null)
       {
           showToast("请选择省市区地址");

           return;

       }
       if (connty==null)
       {
           showToast("请选择省市区地址");

           return;

       }

        String  addr_details =  binding.etAddrDetails.getText().toString();
        if (TextUtils.isEmpty(addr_details))
        {
            showToast("请填写详细地址");
            return;
        }

        boolean   isMoren = binding.swithCheck.isChecked();
        ApiFactory.getApiService().addAddr(User.get().getMyInfo().getToken()
        ,name,phone,provice,city,connty,addr_details,isMoren?"1":"0"
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("添加成功");
                            Intent  intent  =new Intent();
                            setResult(1001,intent);
                            finish();
                        }else
                        {
                            showToast(commResponseBean.getErrMessage());

                        }
                    }
                });


    }

    @Override
    protected void onActionMenuViewClick() {
        super.onActionMenuViewClick();
        delAddr();
    }

    private void delAddr() {
        ApiFactory.getApiService().delAddr(User.get().getMyInfo().getToken(),bean.getId()+"")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("删除成功");
                            Intent  intent  =new Intent();
                            setResult(1001,intent);
                            finish();
                            finish();
                        }
                        else
                        {
                            showToast(commResponseBean.getErrMessage());
                        }
                    }
                });
    }

    /**
     *
     * @param context
     * @param type  0是增加  1是编辑
     */
    public static void start(int code,Context context,int  type) {
        Intent starter = new Intent(context, AddAddrActivity.class);
        starter.putExtra("type",type);
        context.startActivity(starter);
    }




    /**
     *
     * @param context
     * @param type  0是增加  1是编辑
     */
    public static void startForEdResult(int  code,Context context, int  type, AddressBean  bean) {
        Intent starter = new Intent(context, AddAddrActivity.class);
        starter.putExtra("type",type);
        starter.putExtra("bean",bean);
        context.startActivity(starter);
    }




}